import 'package:hzy_normal_network/hzy_normal_network.dart';
import 'package:hzy_normal_tool/hzy_normal_tool.dart';

import '../../tools/index.dart';
import '../models/index.dart';
import '../network/eg_apis.dart';
import '../tools/eg_tools.dart';

class EgVm {
  /// 网络请求
  EgApis api = EgApis();

  /// 数据列表
  List<TuChongItem> itemList = [];

  /// 页面状态
  PageState pageState = PageState.initializedState;

  /// 配置列表数据
  configListData({
    int page = 1,
    bool isShowLoad = false,
  }) async {
    int? psid;
    if (itemList.isNotEmpty) {
      psid = itemList.last.postId;
    }
    List<TuChongItem> list = [];
    HzyNormalResponse res = HzyNormalResponse.success(
      netData: {},
      reqMsg: "",
    );
    res = await api.loadListData(
      page: page,
      lastPostId: psid,
      isShowLoad: isShowLoad,
    );
    if (res.ok) {
      if (page == 1) {
        itemList.clear();
      }

      if (res.data != null) {
        for (final dynamic item in res.data) {
          if (item != null) {
            tryCatch(() {
              TuChongItem model = TuChongItem.fromJson(
                asT<Map<String, dynamic>>(item)!,
              );
              model.heaerImgModel = configImageNormalModel(
                imageUrl: model.imageUrl,
                width: ScreeTool.screenWidth,
                imgWidth: model.imageSize.width,
                imgHeight: model.imageSize.height,
              );
              list.add(model);
            });
          }
        }
      }
    }
    itemList.addAll(list);
    final uniqueList = itemList.map((e) => e.postId).toSet();
    itemList.retainWhere((element) => uniqueList.remove(element.postId));
    pageState = determinePageState(
      totalCount: itemList.length,
      currentPageCount: list.length,
    );
  }
}
